package com.example.gamestore.control;

import com.example.gamestore.Bean.Cart;
import com.example.gamestore.Bean.CartItem;
import com.example.gamestore.Bean.Game;
import com.example.gamestore.service.GameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class CheckTableControl {
    @Autowired
    private GameService gameService;
    @GetMapping("/checkout")
    public String Checkout(HttpSession session){
        session.removeAttribute("orderid");
        session.removeAttribute("error");
        return "checkout";
    }

    @GetMapping("/cart")
    public String Cart(HttpSession session){
        Cart cart = (Cart) session.getAttribute("cart");
        if(cart==null){
            cart=new Cart();
            session.setAttribute("cart",cart);
        }
        return "Cart/Cart";
    }

    @GetMapping("/addcart")
    public String addcart(@RequestParam(name = "id",defaultValue = "1") Integer id, HttpSession session, HttpServletRequest request){
        Game game = gameService.selectGameByid(id);
        System.out.println(game);
        CartItem cartItem=new CartItem(game.getId(),game.getGamename(),1,game.getPrice(),game.getPrice(),game.getImage());
        Cart cart = (Cart) session.getAttribute("cart");
        if(cart==null){
            cart=new Cart();
           session.setAttribute("cart",cart);
        }
        cart.addItem(cartItem);
        String referer = request.getHeader("Referer");
        System.out.println(referer);
        System.out.println(cart);
        return "redirect:/cart";
    }

}
